import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
import '../models/weather_model.dart';
import '../widgets/favorite_button.dart';
import '../services/weather_service.dart';
import '../widgets/temperature_line_chart.dart';

class DetailScreen extends StatefulWidget {
  final CaiyunRealtime weather;
  final String city;
  final CaiyunLifeIndex? lifeIndex;
  final CaiyunDailyForecast? forecast;
  final double? lon;
  final double? lat;
  final List<CustomWeatherReminder>? customReminders;

  const DetailScreen({
    super.key,
    required this.weather,
    required this.city,
    this.lifeIndex,
    this.forecast,
    this.lon,
    this.lat,
    this.customReminders,
  });

  @override
  State<DetailScreen> createState() => _DetailScreenState();
}

class _DetailScreenState extends State<DetailScreen> {
  bool _localeReady = false;
  List<Map<String, dynamic>>? _hourlyWeather;
  bool _loadingHourly = false;
  String? _hourlyError;

  @override
  void initState() {
    super.initState();
    initializeDateFormatting('zh_CN', null).then((_) {
      setState(() {
        _localeReady = true;
      });
    });
    _fetchHourlyWeather();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _checkAndShowWeatherAlert();
    });
  }

  Future<void> _fetchHourlyWeather() async {
    // 仅当天才请求小时天气
    if (widget.forecast == null) {
      setState(() {
        _loadingHourly = true;
      });
      try {
        double? lon = widget.lon;
        double? lat = widget.lat;
        if (lon == null || lat == null) {
          final coords =
              await WeatherService.getCoordinatesFromCity(widget.city);
          lon = coords[0];
          lat = coords[1];
        }
        final data = await WeatherService.getHourlyWeather(lon, lat);
        setState(() {
          _hourlyWeather = data;
          _loadingHourly = false;
        });
      } catch (e) {
        setState(() {
          _hourlyError = e.toString();
          _loadingHourly = false;
        });
      }
    }
  }

  void _checkAndShowWeatherAlert() {
    if (widget.forecast != null) return; // 只对当天实况弹窗
    // 极端天气
    String? alertType;
    String? alertMsg;
    final w = widget.weather;
    if (w.temperature >= 37) {
      alertType = '高温预警';
      alertMsg = '当前温度已达${w.temperature}°C，请注意防暑降温。';
    } else if (w.temperature <= 0) {
      alertType = '低温预警';
      alertMsg = '当前温度已降至${w.temperature}°C，请注意保暖。';
    } else if (w.skycon.contains('RAIN')) {
      alertType = '暴雨预警';
      alertMsg = '当前有降雨，请注意出行安全。';
    } else if (w.skycon.contains('STORM')) {
      alertType = '强对流天气预警';
      alertMsg = '当前有强对流天气，请注意安全。';
    }
    if (alertType != null && alertMsg != null) {
      _showAlertDialog(alertType, alertMsg);
      return;
    }
    // 自定义提醒
    final reminders = widget.customReminders ??
        [
          CustomWeatherReminder(
              condition: '温度高于', threshold: 35, enabled: true),
          CustomWeatherReminder(
              condition: '下雨', weatherType: '雨', enabled: true),
        ];
    for (final reminder in reminders) {
      if (!reminder.enabled) continue;
      if (reminder.condition.contains('温度高于') && reminder.threshold != null) {
        if (w.temperature > reminder.threshold!) {
          _showAlertDialog(
              '天气提醒', '当前温度${w.temperature}°C，已超过设定阈值${reminder.threshold}°C');
          return;
        }
      } else if (reminder.condition.contains('温度低于') &&
          reminder.threshold != null) {
        if (w.temperature < reminder.threshold!) {
          _showAlertDialog(
              '天气提醒', '当前温度${w.temperature}°C，已低于设定阈值${reminder.threshold}°C');
          return;
        }
      } else if (reminder.condition.contains('下雨') ||
          (reminder.weatherType == '雨')) {
        if (w.skycon.contains('RAIN')) {
          _showAlertDialog('天气提醒', '当前有降雨，请注意携带雨具。');
          return;
        }
      }
    }
  }

  void _showAlertDialog(String title, String content) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('知道了'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (!_localeReady) {
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }
    final isForecast = widget.forecast != null;
    final date = isForecast ? widget.forecast!.date : DateTime.now();
    final minTemp = isForecast
        ? widget.forecast!.minTemp.round()
        : widget.weather.temperature.round();
    final maxTemp = isForecast
        ? widget.forecast!.maxTemp.round()
        : widget.weather.temperature.round();
    final skycon = isForecast ? widget.forecast!.skycon : widget.weather.skycon;
    final aqi = isForecast ? widget.forecast!.aqi : widget.weather.aqi;
    final aqiDesc =
        isForecast ? _getAqiLevel(aqi) : widget.weather.aqiDescription;
    final weatherDesc = isForecast
        ? _getWeatherDescription(skycon)
        : _getWeatherDescription(widget.weather.skycon);
    final suggestions = widget.lifeIndex != null
        ? {
            'dressing': widget.lifeIndex!.dressing,
            'uv': widget.lifeIndex!.ultraviolet,
            'sport': widget.lifeIndex!.carWashing,
          }
        : (isForecast
            ? {
                'dressing': '建议穿长袖T恤、牛仔裤等舒适衣物',
                'uv': '紫外线强度中等，建议涂抹防晒霜',
                'sport': '适宜进行各类户外运动',
              }
            : null);

    return Scaffold(
      appBar: AppBar(
        title: Text('${widget.city} 天气详情'),
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.black87),
        titleTextStyle: const TextStyle(
            color: Colors.black87, fontSize: 20, fontWeight: FontWeight.bold),
        centerTitle: true,
        automaticallyImplyLeading: true,
        actions: [
          FavoriteButton(city: widget.city),
        ],
      ),
      backgroundColor: const Color(0xFFE3F2FD),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 日期和温度
              Center(
                child: Column(
                  children: [
                    Text(
                      DateFormat('yyyy年MM月dd日 EEE', 'zh_CN').format(date),
                      style: const TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 10),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(_getWeatherIcon(skycon),
                            size: 48, color: Colors.black54),
                        const SizedBox(width: 20),
                        Text(
                          isForecast
                              ? '${minTemp}°C ~ ${maxTemp}°C'
                              : '${widget.weather.temperature.round()}°C',
                          style: const TextStyle(
                            fontSize: 36,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 30),
              // 天气状况描述
              Card(
                elevation: 3,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '天气状况',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 10),
                      Text(
                        weatherDesc,
                        style: const TextStyle(
                          fontSize: 16,
                          height: 1.5,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 20),
              // 空气质量
              Card(
                elevation: 3,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '空气质量',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 10),
                      Row(
                        children: [
                          Container(
                            padding: const EdgeInsets.all(8.0),
                            decoration: BoxDecoration(
                              color: _getAqiColor(aqiDesc),
                              borderRadius: BorderRadius.circular(8.0),
                            ),
                            child: Text(
                              '$aqi',
                              style: const TextStyle(
                                fontSize: 24,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                              ),
                            ),
                          ),
                          const SizedBox(width: 20),
                          Text(
                            aqiDesc,
                            style: const TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
              // 24小时天气（仅当天显示）
              if (!isForecast) ...[
                const SizedBox(height: 20),
                Card(
                  elevation: 3,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '24小时天气',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 10),
                        if (_loadingHourly)
                          const Center(child: CircularProgressIndicator())
                        else if (_hourlyError != null)
                          Text('获取失败: $_hourlyError',
                              style: const TextStyle(color: Colors.red))
                        else if (_hourlyWeather != null)
                          Builder(
                            builder: (context) {
                              final now = DateTime.now();
                              // 统一转本地时区
                              final List<Map<String, dynamic>> hourlyLocal =
                                  _hourlyWeather!.map((h) {
                                final dt = h['datetime'];
                                return {
                                  ...h,
                                  'datetime': dt.isUtc ? dt.toLocal() : dt,
                                };
                              }).toList();
                              // 找到第一个大于等于当前小时的索引
                              int startIdx = hourlyLocal.indexWhere((h) {
                                final dt = h['datetime'];
                                return dt.year == now.year &&
                                    dt.month == now.month &&
                                    dt.day == now.day &&
                                    dt.hour == now.hour;
                              });
                              if (startIdx == -1) {
                                // 若找不到，取第一个大于当前时间的小时
                                startIdx = hourlyLocal.indexWhere(
                                    (h) => h['datetime'].isAfter(now));
                                if (startIdx == -1) startIdx = 0;
                              }
                              final List<Map<String, dynamic>> displayList =
                                  (hourlyLocal.sublist(startIdx) +
                                          hourlyLocal.sublist(0, startIdx))
                                      .take(24)
                                      .toList();
                              return SizedBox(
                                height: 130, // 原来是110，适当加高，避免内容溢出
                                child: ListView.separated(
                                  scrollDirection: Axis.horizontal,
                                  itemCount: displayList.length,
                                  separatorBuilder: (_, __) =>
                                      const SizedBox(width: 8),
                                  itemBuilder: (context, i) {
                                    final h = displayList[i];
                                    return Container(
                                      width: 60,
                                      padding: const EdgeInsets.all(6),
                                      decoration: BoxDecoration(
                                        gradient: LinearGradient(
                                          colors: [
                                            Colors.blue.withOpacity(0.2),
                                            Colors.white.withOpacity(0.7),
                                          ],
                                          begin: Alignment.topCenter,
                                          end: Alignment.bottomCenter,
                                        ),
                                        borderRadius: BorderRadius.circular(12),
                                        boxShadow: [
                                          BoxShadow(
                                            color: Colors.blue.withOpacity(0.1),
                                            blurRadius: 8,
                                            offset: Offset(0, 4),
                                          ),
                                        ],
                                      ),
                                      child: Column(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                          Text(
                                            DateFormat('HH:mm').format(h['datetime']),
                                            style: TextStyle(
                                              fontSize: 14,
                                              fontWeight: FontWeight.w600,
                                              color: h['datetime'].hour == DateTime.now().hour
                                                ? Colors.blue[800]
                                                : Colors.black87,
                                            ),
                                          ),
                                          const SizedBox(height: 6),
                                          AnimatedSwitcher(
                                            duration: Duration(milliseconds: 300),
                                            child: Icon(
                                              _getWeatherIcon(h['skycon']),
                                              key: ValueKey(h['skycon']),
                                              size: 28,
                                              color: Colors.blue[700],
                                            ),
                                          ),
                                          const SizedBox(height: 6),
                                          Text(
                                            '${h['temp'].round()}°',
                                            style: TextStyle(
                                              fontSize: 18,
                                              fontWeight: FontWeight.bold,
                                              color: Colors.blue[900],
                                            ),
                                          ),
                                          if ((h['precip'] as num) > 0.01)
                                            Column(
                                              children: [
                                                const SizedBox(height: 4),
                                                Container(
                                                  width: 40,
                                                  height: 4,
                                                  decoration: BoxDecoration(
                                                    borderRadius: BorderRadius.circular(2),
                                                    color: Colors.blue.withOpacity(0.3),
                                                  ),
                                                  child: FractionallySizedBox(
                                                    alignment: Alignment.centerLeft,
                                                    widthFactor: (h['precip'] as num).clamp(0, 1).toDouble(),
                                                    child: Container(
                                                      decoration: BoxDecoration(
                                                        borderRadius: BorderRadius.circular(2),
                                                        color: Colors.blue,
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                                Text(
                                                  '${((h['precip'] as num) * 100).round()}%',
                                                  style: TextStyle(
                                                    fontSize: 10,
                                                    color: Colors.blue[800],
                                                  ),
                                                ),
                                              ],
                                            ),
                                        ],
                                      ),
                                    );
                                  },
                                ),
                              );
                            },
                          ),
                      ],
                    ),
                  ),
                ),
              ],
              // 温度趋势图
              if (!isForecast &&
                  _hourlyWeather != null &&
                  _hourlyWeather!.isNotEmpty) ...[
                Padding(
                  padding: const EdgeInsets.only(top: 16.0),
                  child: TemperatureLineChart(
                    temperatures: _get24HourTempsFromNow(_hourlyWeather!),
                    hours: _get24HourHoursFromNow(_hourlyWeather!),
                  ),
                ),
              ],
              // 生活建议
              if (!isForecast) ...[
                Card(
                  elevation: 3,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '生活建议',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 10),
                        _buildSuggestionItem(
                            '穿衣指数', suggestions?['dressing'] ?? '无建议'),
                        const SizedBox(height: 10),
                        _buildSuggestionItem(
                            '紫外线强度', suggestions?['uv'] ?? '无建议'),
                        const SizedBox(height: 10),
                        _buildSuggestionItem(
                            '运动建议', suggestions?['sport'] ?? '无建议'),
                      ],
                    ),
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSuggestionItem(String title, String content) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '$title: ',
          style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
        ),
        Expanded(
          child: Text(
            content,
            style: const TextStyle(fontSize: 15),
          ),
        ),
      ],
    );
  }

  IconData _getWeatherIcon(String skycon) {
    switch (skycon) {
      case 'CLEAR_DAY':
        return Icons.wb_sunny;
      case 'CLEAR_NIGHT':
        return Icons.nightlight_round;
      case 'PARTLY_CLOUDY_DAY':
      case 'PARTLY_CLOUDY_NIGHT':
        return Icons.cloud;
      case 'CLOUDY':
        return Icons.cloud;
      case 'LIGHT_HAZE':
      case 'MODERATE_HAZE':
      case 'HEAVY_HAZE':
        return Icons.waves;
      case 'LIGHT_RAIN':
      case 'MODERATE_RAIN':
      case 'HEAVY_RAIN':
      case 'STORM_RAIN':
        return Icons.grain;
      case 'LIGHT_SNOW':
      case 'MODERATE_SNOW':
      case 'HEAVY_SNOW':
      case 'STORM_SNOW':
        return Icons.ac_unit;
      case 'DUST':
      case 'SAND':
        return Icons.waves;
      case 'FOG':
        return Icons.waves;
      case 'WIND':
        return Icons.air;
      default:
        return Icons.wb_sunny;
    }
  }

  String _getWeatherDescription(String skycon) {
    switch (skycon) {
      case 'CLEAR_DAY':
        return '晴天';
      case 'CLEAR_NIGHT':
        return '晴夜';
      case 'PARTLY_CLOUDY_DAY':
        return '多云';
      case 'PARTLY_CLOUDY_NIGHT':
        return '多云';
      case 'CLOUDY':
        return '阴天';
      case 'LIGHT_HAZE':
        return '轻度雾霾';
      case 'MODERATE_HAZE':
        return '中度雾霾';
      case 'HEAVY_HAZE':
        return '重度雾霾';
      case 'LIGHT_RAIN':
        return '小雨';
      case 'MODERATE_RAIN':
        return '中雨';
      case 'HEAVY_RAIN':
        return '大雨';
      case 'STORM_RAIN':
        return '暴雨';
      case 'LIGHT_SNOW':
        return '小雪';
      case 'MODERATE_SNOW':
        return '中雪';
      case 'HEAVY_SNOW':
        return '大雪';
      case 'STORM_SNOW':
        return '暴雪';
      case 'DUST':
        return '浮尘';
      case 'SAND':
        return '沙尘';
      case 'FOG':
        return '雾';
      case 'WIND':
        return '大风';
      default:
        return '未知';
    }
  }

  String _getAqiLevel(int aqi) {
    if (aqi >= 0 && aqi <= 50) return '优';
    if (aqi <= 100) return '良';
    if (aqi <= 150) return '轻度污染';
    if (aqi <= 200) return '中度污染';
    if (aqi <= 300) return '重度污染';
    return '严重污染';
  }

  Color _getAqiColor(String level) {
    switch (level) {
      case '优':
        return Colors.green;
      case '良':
        return Colors.yellow;
      case '轻度污染':
        return Colors.orange;
      case '中度污染':
        return Colors.red;
      case '重度污染':
        return Colors.purple;
      default:
        return Colors.grey;
    }
  }

  List<double> _get24HourTempsFromNow(List<Map<String, dynamic>> data) {
    final now = DateTime.now();
    int startIdx = data.indexWhere((h) =>
        h['datetime'].year == now.year &&
        h['datetime'].month == now.month &&
        h['datetime'].day == now.day &&
        h['datetime'].hour == now.hour);
    if (startIdx == -1) startIdx = 0;
    final displayList =
        (data.sublist(startIdx) + data.sublist(0, startIdx)).take(24).toList();
    return displayList.map((h) => (h['temp'] as num).toDouble()).toList();
  }

  List<String> _get24HourHoursFromNow(List<Map<String, dynamic>> data) {
    final now = DateTime.now();
    int startIdx = data.indexWhere((h) =>
        h['datetime'].year == now.year &&
        h['datetime'].month == now.month &&
        h['datetime'].day == now.day &&
        h['datetime'].hour == now.hour);
    if (startIdx == -1) startIdx = 0;
    final displayList =
        (data.sublist(startIdx) + data.sublist(0, startIdx)).take(24).toList();
    return displayList
        .map((h) => DateFormat('HH').format(h['datetime']))
        .toList();
  }
}

class DetailScreenRouter extends StatefulWidget {
  const DetailScreenRouter({super.key});

  @override
  State<DetailScreenRouter> createState() => _DetailScreenRouterState();
}

class _DetailScreenRouterState extends State<DetailScreenRouter> {
  @override
  Widget build(BuildContext context) {
    final args =
        ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
    if (args == null) {
      return const Scaffold(
        body: Center(child: Text('无详细天气数据')),
      );
    }
    return DetailScreen(
      weather: args['weather'],
      city: args['city'],
      lifeIndex: args['lifeIndex'],
      forecast: args['forecast'],
      lon: args['lon'],
      lat: args['lat'],
      customReminders: args['customReminders'],
    );
  }
}
